<template>
  <!-- ActivityDetails 活动详情 -->
  <page-meta
    :page-style="`overflow: ${showSharePopup || attachPopupVisible ? 'hidden' : 'visible'}`"
  />
  <PageContainer v-model:enter-options="enterOptions">
    <Loading v-model="loading">
      <view class="container">
        <ActivityDetailMain
          type="register"
          :personnelList="personnelList"
          :organizingUnitList="organizingUnitList"
          :activity-list-res-data="data"
          :richTextData="richTextData"
          @pageScrollTo="pageScrollTo"
        ></ActivityDetailMain>
        <view
          v-if="
            data?.activityStatus !== ActivityStatusEnum.CANCEL &&
            enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE
          "
          class="bot-btns card-shadow"
          id="footer-opration"
        >
          <view
            v-if="
              guidancePopupShow &&
              (data?.activityStatus === ActivityStatusEnum.REGISTRATION_UNDERWAY ||
                data?.activityStatus === ActivityStatusEnum.START) &&
              personnelList?.length
            "
            class="guidance-popup disFlxAC disFlxJC"
          >
            <!-- <view v-if="!isRegistered">
              <view class="guidance-popup__avatar disFlxAC">
                <view class="guidance-popup__avatar--item">
                  <TImage
                    :src="personnelList[0]?.avatar"
                    error-img-type="person"
                    width="100%"
                    height="100%"
                    border-radius="50%"
                  />
                </view>
                <View class="guidance-popup__avatar--item" style="margin-left: -24rpx">
                  <TImage
                    :src="personnelList[1]?.avatar"
                    error-img-type="person"
                    width="100%"
                    height="100%"
                    border-radius="50%"
                  />
                </View>
              </view>
              <view class="guidance-popup__avatar disFlxAC" style="margin-top: -24rpx">
                <view class="guidance-popup__avatar--item">
                  <TImage
                    :src="personnelList[2]?.avatar"
                    error-img-type="person"
                    width="100%"
                    height="100%"
                    border-radius="50%"
                  />
                </view>
                <view class="guidance-popup__avatar--item" style="margin-left: -24rpx">
                  <TImage
                    :src="personnelList[3]?.avatar"
                    error-img-type="person"
                    width="100%"
                    height="100%"
                    border-radius="50%"
                  />
                </view>
              </view>
            </view> -->
            <view v-if="!isRegistered" class="fz-14 ml-8">
              <view>
                <text>多人报名、代人报名</text>
              </view>
              <view>
                <text>均可点击此按钮~</text>
              </view>
            </view>
            <view v-if="isRegistered" class="fz-14 ml-8">
              <view>
                <text>您已报名活动，可点击继续给</text>
              </view>
              <view>
                <text>其他人代报名哦!</text>
              </view>
            </view>
            <!-- <view class="ali-icon fz-14 ml-8">&#xe67b;</view> -->
            <view class="arrows"></view>
          </view>
          <view class="left pl-16">
            <view class="left-btn" @click="attachPopupVisible = true">
              <text class="ali-icon icon-dianhuatianchong icon-style" />
              <text class="text">咨询</text>
            </view>
            <view class="left-btn" v-if="data?.restrictShar" @click="handleShowSharePopup">
              <text class="ali-icon icon-fenxiang-mianxing icon-style" style="color: #2878ff" />
              <text class="text">分享</text>
            </view>
          </view>
          <view v-if="data" class="right px-16">
            <TButtonGroup
              v-if="data.activityTag === ActivityVersionEnum.payActivity"
              position="unset"
              :styles="{ padding: 0 }"
            >
              <TButton
                text="报名记录"
                type="none"
                class="gutter-btn"
                custom-class="h-44 linh-44 br-22 px-16"
                :custom-style="{
                  color: '#2878FF',
                  border: '1px solid #2878FF',
                  boxSizing: 'content-box',
                }"
                @click="toRegistrationRecord"
              />
              <TButton
                v-if="getIsBuyTicket"
                text="立即报名"
                type="primary"
                class="gutter-btn"
                custom-class="h-44 linh-44 br-22 px-16"
                @click="toBuyTickets"
              />
            </TButtonGroup>
            <ActivityBtns
              :item="data"
              v-else
              import-type="details"
              @refresh="__init"
              @after-fnc="afterFnc"
            />
          </view>
        </view>

        <AttachPopup v-model:visible="attachPopupVisible" :attache-vo-list="data?.attacheVoList" />

        <PerfectInfoDialog />
      </view>
    </Loading>
  </PageContainer>

  <CustomShare
    v-if="enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
    v-model:visible="showSharePopup"
    @register="handleCustomShareregister"
  />

  <UniPopup ref="noPermissionPopupRef" borderRadius="32rpx 32rpx 0 0" backgroundColor="#fff">
    <view class="default-color">
      <view class="disFlxCC pa-16">
        <text class="fz-16 mb-12">报名限制详情</text>
        <text class="fz-14 mb-12">您当前身份：{{ cocInfo ? cocInfo.levelName : '普通用户' }}</text>
        <text class="fz-14 mb-12" style="color: #646566">当前类型报名需要以下身份：</text>
        <scroll-view
          class="br-8 pa-12 identity-list"
          :enhanced="true"
          :show-scrollbar="false"
          scroll-y
          enable-flex
        >
          <template v-for="(v, i) in identityList" :key="i">
            <view class="identity-tag fz-12 px-8 py-4 br-2 mr-8 mb-8">
              <text>{{ v.memberLevelName }}</text>
            </view>
          </template>
        </scroll-view>
      </view>
      <TButtonGroup position="unset" :styles="{ padding: '20rpx 32rpx' }">
        <TButton
          text="取消"
          type="none"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22 px-16"
          :custom-style="{
            color: '#2878FF',
            border: '1px solid #2878FF',
            boxSizing: 'content-box',
          }"
          @click="closeNoPermissionPopupRefModel"
        />
        <TButton
          v-if="!cocInfo"
          text="申请成为会员"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22 px-16"
          @click="handleToSelectiveType"
        />
      </TButtonGroup>
    </view>
  </UniPopup>
</template>

<script lang="ts" setup>
  /**  ActivityDetails  活动详情 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { getUrl, navigateTo, onLoad } from '@/router';
  import { ref, getCurrentInstance, watch, computed, watchEffect } from 'vue';
  import {
    activityDetailRegisterList,
    activityDetails,
    getActivityDetailList,
    getActivityPartners,
    prticipantsList,
  } from '@/api/activity';
  import type {
    IActivityListResData,
    IActivityTicketResult,
    IOrganizingUnit,
    IPrticipantsListResData,
  } from '@/api/activity/types';
  import ActivityBtns from '@/components/ActivityItem/ActivityBtnsBtns.vue';
  import Loading from '@/components/Loading/index.vue';
  import {
    onPageScroll,
    onPullDownRefresh,
    onShareAppMessage,
    onShareTimeline,
  } from '@dcloudio/uni-app';

  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';

  import ActivityDetailMain from './components/ActivityDetailMain.vue';
  import {
    ActivityStatusEnum,
    ActivityVersionEnum,
    ApprovalStatusEnum,
  } from '@/enums/activityStatusEnum';
  import type { IRichTextData } from './types';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
  import {
    getActivityPosterData,
    getActivityWxShareData,
    isActivityNumMax,
    toActivityRegistration,
  } from '../utils';
  import AttachPopup from '../components/AttachPopup.vue';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { createMiniCode, toSelectiveType } from '@/utils/dynamicConfig';
  import { addAppShareLog } from '@/api';
  import { useActivityStore } from '@/store/modules/activity';
  import { useUserStore } from '@/store/modules/user';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';

  const { cocInfo } = useUserStore();

  const { setActivityShareCache, setActivityOrderRouteParams } = useActivityStore();

  const { setWxSharePath, createShareQuery, setWxShareTimelineQuery } = useAppShare();

  const [
    register,
    {
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setShareTimelineContent,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      timeline: true,
      copyLink: true,
      insertOffiaccount: true,
      offiaccount: true,
    },
  });

  const customShareLoading = ref(false);
  function handleCustomShareregister(e: any) {

    register(e);
    customShareLoading.value = true;
  }

  const enterOptions = ref<UniApp.GetLaunchOptionsSyncOptions>();

  const _this = getCurrentInstance();
  const loading = ref(true);
  /** 活动id */
  const id = ref<number>(0);

  /** 详情数据 */
  const data = ref<IActivityListResData>();

  const personnelList = ref<IPrticipantsListResData[]>();

  /** 分享弹窗 */
  const showSharePopup = ref(false);

  const attachPopupVisible = ref(false);

  const identityList = ref<IActivityTicketResult['memberIdentityList']>([]);

  /** 获取活动详情数据 */
  async function getData() {
    const detailsId = id.value;
    const r = await activityDetails(detailsId, shareKey.value);
    if (r.onlyOneTicketVo) {
      identityList.value = r.onlyOneTicketVo.memberIdentityList;
    }
    data.value = r;
  }

 const stopWatch =  watchEffect(async () => {
    const v1 = customShareLoading.value
    const v2 = data.value
    const v3 = personnelList.value
    if (!v1 || !v2 || !v3) return;

    if (enterOptions.value?.scene === SceneValuesEnum.TIMELINE_SINGLEPAGE) return;
    const path = setWxSharePath({
      name: 'activityDetails',
      options: { id: id.value },
    });
    const routeQuery = createShareQuery({ id: id.value });

    if (data.value) {
      if (!loading.value) loading.value = true;
      setInternalLinkOptions({
        name: 'activityDetails',
        options: { id: id.value },
      });
      const wxShareOptions = await setWxShareOptions(
        getActivityWxShareData(data.value, path, personnelList.value || []),
      );
      const { id: shareLogId } = await addAppShareLog({
        path: getUrl('activityDetails'),
        query: JSON.stringify(routeQuery),
      });
      setShareLogId(shareLogId);
      const shareTimelineContent = {
        query: setWxShareTimelineQuery(routeQuery),
        title: data.value?.title,
        imageUrl: data.value?.sharUrl || data.value?.coverUrl,
      };
      setShareTimelineContent(shareTimelineContent);

      setActivityShareCache({
        wxShareOptions,
        shareLogId,
        shareTimelineContent,
        activeityData: {
          id: data.value.id,
          title: data.value.title,
          startTime: data.value.startTime,
          endTime: data.value.endTime,
          coverUrl: data.value.coverUrl,
          addressName: data.value.addressName,
        },
      });
      loading.value = false;
      stopWatch()
      const codeImg = await createMiniCode({ shareLogId });
      const posterData = getActivityPosterData(data.value!, codeImg);
      await setPosterDrawData(posterData);
    }
  })

  let refresh: Function | undefined;
  const shareKey = ref<string>();
  const guidancePopupShow = ref(true);

  onLoad<'ActivityDetails'>((op) => {
    id.value = op.scene ? op.scene : op.id;
    shareKey.value = op.shareKey;
    refresh = op.refresh;
    __init();
  });

  async function handleShowSharePopup() {
    showSharePopup.value = true;
  }

  async function __init() {
    showSharePopup.value = false;
    customShareLoading.value = false
    loading.value = true;
    await getData();
    await getPrticipantsList();
    await queryActivityPartners();
    await queryActivityDetailList();
    setTimeout(() => {
      guidancePopupShow.value = false;
    }, 3000);
    uni.stopPullDownRefresh()
    customShareLoading.value = true
    loading.value = false;
  }

  const getIsBuyTicket = computed(() => {
    if (!data.value) return false;
    const { activityStatus, enrollRestrict, maxNum, passedNum } = data.value;
    let isBuyTicket = false;
    if (
      activityStatus === ActivityStatusEnum.REGISTRATION_UNDERWAY ||
      activityStatus === ActivityStatusEnum.START
    ) {
      isBuyTicket = true;
    }

    if (enrollRestrict && isActivityNumMax(maxNum, passedNum)) {
      isBuyTicket = false;
    }

    return isBuyTicket;
  });

  /** 报名记录 */
  function toRegistrationRecord() {
    if (data.value) {
      const { activityStatus, enrollRestrict, maxNum, passedNum } = data.value;

      setActivityOrderRouteParams(data.value);
      navigateTo({
        name: 'registrationRecord',
        options: {
          isBuyTicket: getIsBuyTicket.value,
          shareKey: shareKey.value,
        },
      });
    }
  }

  /** 购票 */
  function toBuyTickets() {
    if (data.value) {
      const orderCode = data.value.orderCode || '';
      if (orderCode) {
        uni.showModal({
          title: '报名提示',
          content: '您有一个报名待支付订单，是否去支付？',
          cancelColor: '#969799',
          cancelText: '重新报名',
          confirmColor: '#2878FF',
          confirmText: '去支付',
          success: ({ confirm }) => {
            if (confirm) {
              /** 跳转订单详情 */
              navigateTo({
                name: 'activityRegisterOrder',
                options: {
                  orderCode,
                  callback: () => afterFnc(),
                },
              });
            } else {
              /** 重新报名 */
              toSelectTicketType();
            }
          },
        });
        return;
      } else {
        toSelectTicketType();
      }
    }
  }

  function toSelectTicketType() {
    if (data.value) {
      const { onlyOneTicketVo } = data.value;
      setActivityOrderRouteParams(data.value);
      if (onlyOneTicketVo && onlyOneTicketVo.memberIdentityList?.length) {
        openNoPermissionPopupRefModel();
        return;
      }
      toActivityRegistration({
        data: data.value,
        shareKey: shareKey.value,
        isVerifyNumber: true,
      });
    }
  }

  function afterFnc() {
    __init();
    refresh?.();
  }

  onPullDownRefresh(() => {
    __init();
  });

  /**
   * 是否已报名
   */
  const isRegistered = computed(() => {
    return (
      data.value?.register &&
      [
        ApprovalStatusEnum.PASSED,
        ApprovalStatusEnum.UNDERREVIEW,
        ApprovalStatusEnum.WAITPARTICIPATEIN,
        ApprovalStatusEnum.CANCELING,
      ].includes(data.value?.register?.approvalStatus)
    );
  });

  /**报名人员 */
  async function getPrticipantsList() {
    const r = await activityDetailRegisterList(data.value!.id!);
    personnelList.value = r;
  }

  /**举办单位数据 */

  const organizingUnitList = ref<IOrganizingUnit[]>([]);
  const queryActivityPartners = async () => {
    organizingUnitList.value = await getActivityPartners(data.value!.id);
  };

  /**富文本列表 */
  const richTextData = ref<IRichTextData[]>([]);
  const queryActivityDetailList = async () => {
    const res = await getActivityDetailList(data.value!.id);
    richTextData.value = res.map((item) => {
      return {
        title: item.moduleName,
        id: 'id' + item.id,
        top: 0,
        height: 0,
        content: item.introduce,
        isShow: true,
      };
    });
  };

  function openNoPermissionPopupRefModel() {
    (_this?.refs['noPermissionPopupRef'] as any).open('bottom');
  }

  function closeNoPermissionPopupRefModel() {
    (_this?.refs['noPermissionPopupRef'] as any).close();
  }

  function handleToSelectiveType() {
    toSelectiveType(
      {
        linkUrl: 'selectiveType',
        isRedirectTo: true,
      },
      () => {},
      true,
    );
  }

  const pageScrollTo = (id: string, fn: Function) => {
    uni.pageScrollTo({
      selector: id,
      duration: 300,
      success: () => {
        fn();
      },
    });
  };

  onPageScroll(() => {});
  onShareAppMessage(() => ({}));
  onShareTimeline(() => ({}));
</script>
<style lang="scss" scoped>
  .container {
    min-height: 100vh;
  }
  .bot-btns {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 128rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    // padding: 20rpx 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .guidance-popup {
      position: absolute;
      top: -160rpx;
      right: 32rpx;
      background: linear-gradient(90deg, #89b5ff 0%, #2878ff 100%);
      border-radius: 80rpx;
      // width: 368rpx;
      height: 80rpx;
      padding: 16rpx 24rpx;
      color: #fff;
      .guidance-popup__avatar {
        .guidance-popup__avatar--item {
          width: 48rpx;
          height: 48rpx;
          border-radius: 50%;
          border: 1px solid #fff;
          flex-shrink: 0;
        }
      }
      .arrows {
        width: 32rpx;
        height: 32rpx;
        position: absolute;
        right: 64rpx;
        bottom: -26rpx;
        z-index: -1;
        background: #2878ff;
        clip-path: polygon(0 0, 100% 0, 0 100%, 0 0);
      }
    }

    .left {
      display: flex;
      .left-btn {
        width: 100rpx;
        height: 100rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 8rpx;
        color: #999996;
        .icon-style {
          font-size: 40rpx;
        }
        .text {
          font-size: 24rpx;
          line-height: 32rpx;
        }
      }
    }

    .right {
      flex: 1;
    }
  }

  .info-handle-btn {
    display: flex;
    align-items: center;
    flex: 1;
    position: relative;
    height: 40rpx;
    > view {
      // width: 33.33%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #333;
      font-weight: 400;
      position: relative;
      margin-left: 30rpx;
      &:nth-child(2) {
        // border-left: none;
        &::after {
          content: '';
          position: absolute;
          left: -15rpx;
          top: 0;
          width: 4rpx;
          height: 100%;
          background-color: #ddd;
        }
      }
      > button {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 9;
        opacity: 0;
      }
      > .ali-icon {
        font-size: 48rpx;
        color: #ef823a;
        margin-right: 15rpx;
      }
      > image {
        width: 48rpx;
        height: 48rpx;
        margin-right: 15rpx;
      }
    }
  }

  .info-handle-btn {
    margin-top: 30rpx;
    justify-content: flex-end;
    > view {
      width: auto;
    }
  }

  .identity-list {
    width: calc(100% - 64rpx);
    height: 340rpx;
    border: 1px solid #ebedf0;
    .identity-tag {
      display: inline-block;
      color: #2878ff;
      background-color: #d0f7ff;
      width: fit-content;
    }
  }
</style>
